package com.jillchen.grpc.client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class TypeConverter {
    /**
     * byte[]转String
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String bytesToString(byte[] bytes) throws Exception{
        String result = new String(bytes,"UTF-8");
        return result;
    }

    /**
     * String转byte[]
     * @param str
     * @return
     */
    public static byte[] StringToBytes(String str){
        byte[] bytes = str.getBytes();
        return bytes;
    }


    /**
     * InputStream转String
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String InputStreamToString(InputStream inputStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] data = new byte[bufferSize];
        int count = -1;
        while((count = inputStream.read(data,0,bufferSize)) != -1){
            outputStream.write(data,0,count);
            data = null;
        }
        return new String(outputStream.toByteArray(),"UTF-8");
    }

    /**
     * InputStream转Byte[]
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] InputStreamToBytes(InputStream inputStream) throws Exception{
        int bufferSize = 1024;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[bufferSize];
        int count = -1;
        while((count = inputStream.read(data,0,bufferSize))!= -1){
            outputStream.write(data,0,count);
            data = null;
        }

        return outputStream.toByteArray();
    }

    /**
     * byte[]转InputStream
     * @param bytes
     * @return
     * @throws Exception
     */
    public static InputStream BytesToInputStream(byte[] bytes) throws Exception{
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        return is;
    }
}
